<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图-->
    <el-card>
      <!--添加角色按钮区-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!--角色列表区-->
      <el-table :data="rolesList" border stripe>
        <!--展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!--一级权限-->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--二三级权限-->
              <el-col :span="19">
                <!--通过for循环 嵌套渲染二级权限-->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      :class="['vcenter']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--索引列-->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditRoleDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--对话框设置区域-->

    <!--添加用户 对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
    >
      <span>
        <!--内容主体区-->
        <el-form
          ref="addRoleFormRef"
          :model="addRoleForm"
          label-width="90px"
          :rules="addRoleFormRules"
        >
          <el-form-item label="角色" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改角色信息对话框-->
    <el-dialog
      title="修改角色"
      :visible.sync="editRoleDialogVisible"
      width="50%"
    >
      <!--表单内容区-->
      <span>
        <el-form
          :model="editRoleForm"
          :rules="editRoleFormRules"
          ref="editRoleFormRef"
          label-width="90px"
        >
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!--底部区域-->
      <span>
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!--分配权限弹出对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="showSetRightDialogVisible"
      width="30%"
      @close="setRightDialogClosed"
    >
      <!--树形控件-->
      <el-tree
        show-checkbox
        :data="rightList"
        :props="treeProps"
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有角色列表数据
      rolesList: [],

      //添加角色
      //控制添加角色对话框的展开与关闭
      addRoleDialogVisible: false,
      //添加角色表单数据
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      //添加角色的表单校验规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述内容', trigger: 'blur' },
          { min: 3, max: 15, message: '描述内容不宜太短', trigger: 'blur' },
        ],
      },

      //修改角色
      //弹窗
      editRoleDialogVisible: false,
      //修改角色数据
      editRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      //修改角色表单校验规则
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },

      //分配权限
      //弹窗
      showSetRightDialogVisible: false,
      //权限列表
      rightList: [],
      //树形控件
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      //默认选中的结点id值
      defKeys: [],
      //选中行的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }

      this.rolesList = res.data
      //   console.log(this.rolesList)
    },

    //点击添加角色
    addRoleInfo() {
      //发起请求
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 200) {
          this.$message.error('添加角色失败！')
        }
        this.$message.success('成功添加角色！')
        this.addRoleDialogVisible = false
        this.getRolesList()
      })
    },

    //点击删除角色
    async removeRoleById(id) {
      // console.log(id);
      //弹出提示框（element-UI）
      //此时如果点击确定，则返回confirm字符串，点击取消会报错，用catch捕获错误并返回给函数，则返回值是字符串cancel
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('删除取消!')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('成功删除角色！')
      this.getRolesList()
    },

    //点击展示修改角色

    //展示修改信息弹窗
    async showEditRoleDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    //点击提交修改角色信息 validate => 通过校验规则，可以调用回调函数callback（valid），获取valid值并使用
    changeRoleInfo() {
      this.$refs.editRoleFormRef.validate(async (valid) => {
        if (!valid) return
        // console.log(this.editRoleForm.roleId);
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色信息失败！')
        }
        this.editRoleDialogVisible = false
        this.getRolesList()
        this.$message.success('成功修改角色信息！')
      })
    },

    //根据id删除权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除!')
      }
      // console.log('删除成功！');
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      role.children = res.data
    },

    //分配权限
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      this.rightList = res.data
      // console.log(this.rightList)

      //递归获取三级结点id
      this.getLeafKeys(role, this.defKeys)

      this.showSetRightDialogVisible = true
    },

    //通过递归的形式获取角色下所有三级权限的id，并保存到defKeys数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },

    //监听对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },

    //给角色分配权限
    async allotRights() {
      const refKeys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]

      const idStr = refKeys.join(',')
      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})

      if(res.meta.status !== 200){
        this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')

      this.getRolesList()
      this.showSetRightDialogVisible = false
    }
  },
}
</script>

<style>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>